// pages/setMeal/setMeal.js
const app = getApp();
import {
  postRequest,
  getRequest,
  postParamsRequest
} from '../../api/request'
import {
  sortToBig,
} from '../../utils/util'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    themeColor: app.globalData.themeColor,
    subColor: app.globalData.subColor,
    btnColor: app.globalData.btnColor,
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    VerticalNavTop: 0,
    setMealInfo: {}, //套餐信息
    showAddShoppingCar: false,
    goodsSpec: {},
  },

  //阻止冒泡事件
  handmiddle(e) {},

  //返回上一页
  backPage() {
    wx.navigateBack({
      delta: 1
    })
  },

  //套餐数量减少时
  onMealSubGoods() {
    let data = this.data.setMealInfo;
    if (data.count <= 1) {
      return;
    } else {
      data.count -= 1;
    }
    this.setData({
      setMealInfo: data,
    })
  },
  //套餐数量增加时
  onMealAddGoods() {
    let data = this.data.setMealInfo;
    console.log(data);
    if (data.count >= data.stock) {
      wx.showToast({
        title: '无库存',
        icon: "none",
      })
      return;
    }
    data.count += 1;

    this.setData({
      setMealInfo: data,
    })
  },

  //选择套餐时
  onSelectGoods(e) {
    let index1 = e.currentTarget.dataset.index1;
    let index2 = e.currentTarget.dataset.index2;
    //console.log(index1);
    //console.log(index2);
    let data = this.data.setMealInfo;
    if (data.combination[index1].combinationItem[index2].goodsInfo.stock <= 0) {
      wx.showToast({
        title: '已售罄',
        icon: 'none'
      })
      return;
    }

    //多选1
    if (data.combination[index1].selectQuantity == 1) {
      if (data.combination[index1].combinationItem[index2].goodsInfo.count == 0) {
        data.combination[index1].combinationItem[index2].goodsInfo.count = 1;
        data.combination[index1].combinationItem.forEach((item, index) => {
          if (index != index2) {
            item.goodsInfo.count = 0;
          }
        });
      } else {
        if (data.combination[index1].combinationItem[index2].selectType == 1) {
          wx.showToast({
            title: '该商品为必选',
            icon: 'none'
          })
          return;
        } else {
          data.combination[index1].combinationItem[index2].goodsInfo.count = 0;
        }
      }
    } else {
      //多选多
      //计算选中的数量
      let selectNum = 0;
      data.combination[index1].combinationItem.forEach((item, index) => {
        if (item.goodsInfo.count > 0) {
          selectNum += item.goodsInfo.count;
        }
      });

      if (data.combination[index1].combinationItem[index2].goodsInfo.count == 0) {
        if (selectNum >= data.combination[index1].selectQuantity) {
          wx.showToast({
            title: '只能选 ' + data.combination[index1].selectQuantity + ' 个',
            icon: 'none'
          })
          return;
        } else {
          data.combination[index1].combinationItem[index2].goodsInfo.count = 1;
        }
      } else {
        if (data.combination[index1].combinationItem[index2].selectType == 1) {
          wx.showToast({
            title: '该商品为必选',
            icon: 'none'
          })
          return;
        } else {
          data.combination[index1].combinationItem[index2].goodsInfo.count = 0;
        }
      }
    }
    console.log(data);
    this.setData({
      setMealInfo: data,
    });
  },

  //商品复选减少时
  onGoodSubGoods(e) {
    let index1 = e.currentTarget.dataset.index1;
    let index2 = e.currentTarget.dataset.index2;
    let type = e.currentTarget.dataset.type; //1：卡片点击，2：定制点击
    //console.log(index1);
    //console.log(index2);
    let data = this.data.setMealInfo;
    if (data.combination[index1].combinationItem[index2].goodsInfo.count == 0) {
      return;
    }
    if (data.combination[index1].combinationItem[index2].selectType == 1 && data.combination[index1].combinationItem[index2].goodsInfo.count == 1) {
      wx.showToast({
        title: '该商品为必选',
        icon: 'none'
      })
      return;
    } else {
      data.combination[index1].combinationItem[index2].goodsInfo.count -= 1;
    }
    if (type == 1) {
      this.setData({
        setMealInfo: data,
      });
    } else {
      this.setData({
        goodsSpec: data.combination[index1].combinationItem[index2].goodsInfo
      });
    }

  },
  //商品复选增加时
  onGoodAddGoods(e) {
    let index1 = e.currentTarget.dataset.index1;
    let index2 = e.currentTarget.dataset.index2;
    let type = e.currentTarget.dataset.type; //1：卡片点击，2：定制点击
    console.log(index1);
    console.log(index2);
    let data = this.data.setMealInfo;
    //计算选中的数量
    let selectNum = 0;
    data.combination[index1].combinationItem.forEach((item, index) => {
      if (item.goodsInfo.count > 0) {
        selectNum += item.goodsInfo.count;
      }
    });


    if (selectNum >= data.combination[index1].selectQuantity) {
      wx.showToast({
        title: '只能选 ' + data.combination[index1].selectQuantity + ' 个',
        icon: 'none'
      })
      return;
    } else {
      //判断不能大于最大购买数
      if (data.combination[index1].combinationItem[index2].maxSelectQuantity <= data.combination[index1].combinationItem[index2].goodsInfo.count) {
        wx.showToast({
          title: '最大购买数为 ' + data.combination[index1].combinationItem[index2].maxSelectQuantity,
          icon: 'none'
        })
      } else {
        data.combination[index1].combinationItem[index2].goodsInfo.count += 1;
      }
    }

    console.log(data);
    if (type == 1) {
      this.setData({
        setMealInfo: data,
      });
    } else {
      this.setData({
        goodsSpec: data.combination[index1].combinationItem[index2].goodsInfo
      });
    }
  },

  //规格点击时
  clickSpecItem(e) {
    let cIndex = e.currentTarget.dataset.index;
    let cIndex2 = e.currentTarget.dataset.index2;
    let data = this.data.goodsSpec;
    data.goodsSpec.forEach((item, index) => {
      item.specItem.forEach((item2, index2) => {
        if (index == cIndex) {
          if (index2 == cIndex2) {
            item2.checked = true;
          } else {
            item2.checked = false;
          }
        }
      });
    });
    data.count = 1;
    this.setData({
      goodsSpec: data,
    })
    this.undateAddShoppingData();
  },

  //属性选择-----------------------------------------------------开始
  //点击加属性时
  addGoodsAtt(e) {
    let index1 = e.currentTarget.dataset.index1;
    let index2 = e.currentTarget.dataset.index2;
    //console.log(index1);
    //console.log(index2);
    console.log(this.data.goodsSpec.goodsAttrType[index1]);

    if(this.data.goodsSpec.goodsAttrType[index1].goodsAttr[index2].isSellOut == 1){
      wx.showToast({
        title: '已沽清',
        icon: 'none',
      })
      return;
    }

    //判断是否是可复选
    if (this.data.goodsSpec.goodsAttrType[index1].childrenSelectType == 1) {
      this.data.goodsSpec.goodsAttrType[index1].goodsAttr[index2].count += 1;
    } else {
      this.data.goodsSpec.goodsAttrType[index1].goodsAttr[index2].count = this.data.goodsSpec.goodsAttrType[index1].goodsAttr[index2].count == 1 ? 0 : 1;
    }
    //判断是否可多选
    if (this.data.goodsSpec.goodsAttrType[index1].multipleChoice == 0) {
      if (this.data.goodsSpec.goodsAttrType[index1].goodsAttr[index2].count > 0) {
        this.data.goodsSpec.goodsAttrType[index1].goodsAttr.forEach((item3, index3) => {
          if (index3 != index2) {
            item3.count = 0;
          }
        });
      }
    }

    this.setData({
      goodsSpec: this.data.goodsSpec,
    })
    this.undateAddShoppingData();
  },
  //点击减属性时
  subGoodsAtt(e) {
    let index1 = e.currentTarget.dataset.index1;
    let index2 = e.currentTarget.dataset.index2;
    //console.log(index1);
    //console.log(index2);
    console.log(this.data.goodsSpec.goodsAttrType[index1]);
    if (this.data.goodsSpec.goodsAttrType[index1].goodsAttr[index2].count <= 0) {
      return;
    }
    this.data.goodsSpec.goodsAttrType[index1].goodsAttr[index2].count -= 1;
    this.setData({
      goodsSpec: this.data.goodsSpec,
    })
    this.undateAddShoppingData();
  },
  //属性选择-----------------------------------------------------结束

  //关闭套餐定制
  hideAddShoppingCar(e) {
    this.setData({
      showAddShoppingCar: false
    })
  },

  //打开套餐定制
  showAddShoppingCar(e) {
    let index1 = e.currentTarget.dataset.index1;
    let index2 = e.currentTarget.dataset.index2;

    let data2 = this.data.setMealInfo;
    //已经选中时不做判断
    if (data2.combination[index1].combinationItem[index2].goodsInfo.count <= 0) {
      //计算选中的数量
      let selectNum = 0;
      data2.combination[index1].combinationItem.forEach((item, index) => {
        if (item.goodsInfo.count > 0) {
          selectNum += item.goodsInfo.count;
        }
      });


      if (selectNum >= data2.combination[index1].selectQuantity) {
        wx.showToast({
          title: '只能选 ' + data2.combination[index1].selectQuantity + ' 个',
          icon: 'none'
        })
        return;
      } else {
        //判断不能大于最大购买数
        if (data2.combination[index1].combinationItem[index2].maxSelectQuantity <= data2.combination[index1].combinationItem[index2].goodsInfo.count) {
          wx.showToast({
            title: '最大购买数为 ' + data2.combination[index1].combinationItem[index2].maxSelectQuantity,
            icon: 'none'
          })
        }
      }
    }
    let data = this.data.setMealInfo.combination[index1].combinationItem[index2].goodsInfo;
    data.count = 1;
    this.setData({
      showAddShoppingCar: true,
      goodsSpec: data,
    })
    this.undateAddShoppingData();
  },
  //初始化套餐商品选择
  initGoods(e) {
    let index1 = e.currentTarget.dataset.index1;
    let index2 = e.currentTarget.dataset.index2;
    //初始化

    let data = this.data.setMealInfo.combination[index1].combinationItem[index2].goodsInfo;
    data.index1 = index1;
    data.index2 = index2;

    //选规格
    //默认选中第一个规格，单规格则清空
    if (data.isSku == 0) {
      data.goodsSpec = [];
    } else {
      data.goodsSpec.forEach((item, index) => {
        item.specItem.forEach((item2, index2) => {
          if (index2 == 0) {
            item2.checked = true;
          } else {
            item2.checked = false;
          }
        });
      });
    }


    data.count = 1;
    //初始化属性
    data.goodsAttrType.forEach((item, index) => {
      //判断是否必选
      item.goodsAttr.forEach((item2, index2) => {
        item2.count = 0;
      });
    });
    this.setData({
      goodsSpec: data,
    })
    this.undateAddShoppingData();
  },
  //更新添加购物车的价格和规格文字，选择规格,选择的属性等
  undateAddShoppingData() {
    let data = this.data.goodsSpec;
    let selectIds = [];
    let goodsSkuName = [];

    //如果无规格则赋值0
    if (data.goodsSku.length > 0) {
      data.goodsSpec.forEach((item, index) => {
        item.specItem.forEach((item2, index2) => {
          if (item2.checked) {
            selectIds.push(item2.id);
            goodsSkuName.push(item2.itemName);
          }
        });
      });
      data.goodsSkuName = '[' + goodsSkuName.join(",") + "]";
      //小到大排序
      let specsId = sortToBig(selectIds).join("_");
      data.goodsSku.forEach((item, index) => {
        if (item.specsId == specsId) {
          data.shopPrice = item.shopPrice * 1;
          data.skuId = item.id;
          data.skuStock = item.stock;
        }
      });
    } else {
      data.skuId = 0;
      data.skuStock = data.stock;
    }
    //计算属性价格
    let attPrice = 0;
    let goodsArrName = "";
    let goodsArrIds = "";
    //console.log(data.goodsAttrType);
    data.goodsAttrType.forEach((item, index) => {
      item.goodsAttr.forEach((item2, index2) => {
        attPrice = attPrice + item2.price * item2.count;
        if (item2.count != 0) {
          if (item2.count == 1) {
            goodsArrName += item2.attrName + ","
          } else {
            goodsArrName += item2.attrName + "*" + item2.count + ","
          }
          goodsArrIds += item2.attrId + "*" + item2.count + ","
        }
      });
    });
    if (goodsArrName != '') {
      data.goodsArrName = goodsArrName.substring(0, goodsArrName.length - 1);
    } else {
      data.goodsArrName = goodsArrName
    }
    data.goodsArrIds = goodsArrIds;
    
    data.shopPrice = (data.shopPrice * 1 + attPrice).toFixed(2) * 1;
    //商品价格+属性价格
    this.setData({
      goodsSpec: data,
    })
  },
  //选好了
  sureGoods() {
    this.undateAddShoppingData();
    let data = this.data.goodsSpec;
    //判断是否有必填属性未填
    let haveMust = false;
    for (let i = 0; i < this.data.goodsSpec.goodsAttrType.length; i++) {
      if (this.data.goodsSpec.goodsAttrType[i].isMustChoice == 1) {
        haveMust = true;
        for (let j = 0; j < this.data.goodsSpec.goodsAttrType[i].goodsAttr.length; j++) {
          if (this.data.goodsSpec.goodsAttrType[i].goodsAttr[j].count > 0) {
            haveMust = false;
          }
        }
        if (haveMust) {
          wx.showToast({
            title: this.data.goodsSpec.goodsAttrType[i].typeName + '未选择',
            icon: 'none'
          })
          return;
        }
      }
    }
    this.data.setMealInfo.combination[data.index1].combinationItem[data.index2].goodsInfo = data;
    this.setData({
      goodsSpec: data,
      setMealInfo: this.data.setMealInfo,
      showAddShoppingCar: false,
    })
  },

  //加入购物车
  addCart() {
    let data = this.data.setMealInfo;
    for (let i = 0; i < data.combination.length; i++) {
      //该类型选中的商品数量
      let goodsNum = 0;
      for (let j = 0; j < data.combination[i].combinationItem.length; j++) {
        goodsNum += data.combination[i].combinationItem[j].goodsInfo.count;
      }
      if (data.combination[i].selectQuantity != goodsNum) {
        wx.showToast({
          title: '请选择 ' + data.combination[i].name + ' 商品',
          icon: "none"
        })
        return;
      }
    }
    console.log(data);
    console.log(app.globalData.cartList);
    let shoppingCarGoodsList = app.globalData.cartList;
    let packageList = [];
    //获取所有选中的套餐商品
    data.combination.forEach((item, index) => {
      item.combinationItem.forEach((item2, index2) => {
        //大于0就是选中的
        if (item2.goodsInfo.count > 0) {
          //获取已经选中得属性
          let attrList = [];
          item2.goodsInfo.goodsAttrType.forEach((item, index) => {
            item.goodsAttr.forEach((item2, index2) => {
              if (item2.count > 0) {
                attrList.push({
                  count: item2.count,
                  id: item2.attrId,
                  price: item2.price,
                });
              }
            });
          });
          packageList.push({
            attrList: attrList,
            count: item2.goodsInfo.count * item2.defaultQuantity,
            goodsId: item2.goodsInfo.id,
            skuId: item2.goodsInfo.skuId,
            goodsName: item2.goodsName,
            goodsSkuName: item2.goodsInfo.goodsSkuName,
            goodsArrName: item2.goodsInfo.goodsArrName,
          });
        }
      });
    });

    let obj = {
      checked: true,
      id: data.id,
      attrList: [],
      cateId: data.goodsCateId,
      count: data.count,
      goodsId: data.id,
      packageList: packageList,
      packageListString: JSON.stringify(packageList),
      skuId: 0,
      thumbUrl: data.thumbUrl,
      goodsName: data.goodsName,
      goodsSkuName: "",
      goodsArrName: "",
      goodsArrIds: "",
      shopPrice: data.shopPrice,
      originPrice: data.originPrice,
    }
    console.log(obj);
    //是否已经存在
    let isHaveGoods = false;
    shoppingCarGoodsList.forEach((item, index) => {
      //商品相等，规格相等，属性相等
      if (item.id == obj.id && item.skuId == obj.skuId && obj.goodsArrIds == obj.goodsArrIds && item.packageListString == obj.packageListString) {
        item.count += obj.count;
        isHaveGoods = true;
      }
    });
    //不存在时
    if (!isHaveGoods) {
      shoppingCarGoodsList.push(obj);
    }
    app.globalData.cartList = shoppingCarGoodsList;
    app.globalData.isOpenCart = true;
    wx.navigateBack();
  },
  //初始化数据
  initData() {
    console.log(app.globalData.setMealInfo);
    let data = app.globalData.setMealInfo;
    data.count = 1;
    data.combination.forEach((item, index) => {
      item.combinationItem.forEach((item2, index2) => {

        //初始化商品数据，规格，属性
        item2.goodsInfo.index1 = index;
        item2.goodsInfo.index2 = index2;

        //数量，必选项选择为1
        if (item2.selectType == 1) {
          item2.goodsInfo.count = 1;
        } else {
          item2.goodsInfo.count = 0;
        }

        //选规格
        //默认选中第一个规格
        item2.goodsInfo.goodsSpec.forEach((item3, index3) => {
          item3.specItem.forEach((item4, index4) => {
            if (index4 == 0) {
              item4.checked = true;
            } else {
              item4.checked = false;
            }
          });
        });
        //初始化属性
        item2.goodsInfo.goodsAttrType.forEach((item3, index3) => {
          //判断是否必选
          item3.goodsAttr.forEach((item4, index4) => {
            item4.count = 0;
          });
        });


        //计算
        let selectIds = [];
        let goodsSkuName = [];
        item2.goodsInfo.goodsSpec.forEach((item3, index3) => {
          item3.specItem.forEach((item4, index4) => {
            if (item4.checked) {
              selectIds.push(item4.id);
              goodsSkuName.push(item4.itemName);
            }
          });
        });
        item2.goodsInfo.goodsSkuName = '[' + goodsSkuName.join(",") + "]";
        //小到大排序
        let specsId = sortToBig(selectIds).join("_");
        item2.goodsInfo.goodsSku.forEach((item3, index3) => {
          if (item3.specsId == specsId) {
            item2.goodsInfo.shopPrice = item3.shopPrice * 1;
            item2.goodsInfo.skuId = item3.id;
            item2.goodsInfo.skuStock = item3.stock;
          }
        });
        //计算属性价格
        let attPrice = 0;
        let goodsArrName = "";
        let goodsArrIds = "";
        //console.log(data.goodsAttrType);
        item2.goodsInfo.goodsAttrType.forEach((item3, index3) => {
          item3.goodsAttr.forEach((item4, index4) => {
            attPrice = attPrice + item4.price * item4.count;
            if (item4.count != 0) {
              if (item4.count == 1) {
                goodsArrName += "," + item4.attrName
              } else {
                goodsArrName += "," + item4.attrName + "*" + item4.count
              }
              goodsArrIds += item4.attrId + "*" + item4.count + ","
            }
          });
        });
        item2.goodsInfo.skuId = 0;
        item2.goodsInfo.goodsArrName = goodsArrName;
        item2.goodsInfo.goodsArrIds = goodsArrIds;
        item2.goodsInfo.shopPrice = (item2.goodsInfo.shopPrice * 1 + attPrice).toFixed(2) * 1;
      });
    });
    this.setData({
      setMealInfo: data,
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {

    let that = this;
    //如果没有token,则需要重新登录获取个人信息等，避免缺少id导致数据无法获取
    if (app.token == "" || app.token == undefined) {
      app.initLogin().then(res => {
        that.initData();
      }).catch(err => {})
    } else {
      that.initData();
    }

    setTimeout(function () {
      that.setData({
        VerticalNavTop: 140,
      });
    }, 300);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})